package com.example.securitycheck.util;

import android.widget.Toast;

import com.example.securitycheck.MainActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

public class HttpUrl {
    private static String url = "http://localhost:9090/security/SecurityCheck";  //用本机的ip地址代替localhost或127.0.0.1

    /**
     * get网络请求
     */
    public static JSONObject requestGet(Map<String, String> map, String sort) {
        StringBuilder stringBuilder = new StringBuilder(sort);
        JSONObject jsonObject = null;
        String result = "";
        int pos = 0;
        if (null != map) {
            for (String key : map.keySet()) {
                if (pos == 0) {
                    stringBuilder.append("?");
                }
                if (pos > 0) {
                    stringBuilder.append("&");
                }
                try {
                    stringBuilder.append(String.format("%s=%s", key, URLEncoder.encode(map.get(key), "utf-8")));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                pos++;
            }
            String requestUrl = url + stringBuilder.toString();
            //重点
            try {
                //新建一个url对象
                URL urls = new URL(requestUrl);
                //打开一个 HttpURLConnection 连接
                HttpURLConnection httpURLConnection = (HttpURLConnection) urls.openConnection();
                //设置连接主机超时时间
                httpURLConnection.setConnectTimeout(5 * 100);
                //设置从主机读取超时
                httpURLConnection.setReadTimeout(5 * 100);
                //设置是否使用缓存
                httpURLConnection.setUseCaches(true);
                //设置为 get 请求
                httpURLConnection.setRequestMethod("GET");  //get 和post有什么区别？
                //设置请求头信息
                httpURLConnection.setRequestProperty("Content-Type", "application/json");
                //设置客户端与服务连接类型
                httpURLConnection.addRequestProperty("Content-Type", "Keep-Alive");

                //开始连接
                httpURLConnection.connect();   // 这里如果不管的话，请求网络会报错
                //判断请求是否成功
                if (httpURLConnection.getResponseCode() == 200) {
                    //获取返回的json数据
                    result = streamToString(httpURLConnection.getInputStream());
                    //解析json数据
                     jsonObject = new JSONObject(result);
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return jsonObject;
    }

    /**
     * post网络请求
     */
    public static JSONObject requestPost(Map<String, String> map, String sort) {
        StringBuilder stringBuilder = new StringBuilder(sort);
        JSONObject jsonObject = null;
        String result = "";
        int pos = 0;
        if (null != map) {
            for (String key : map.keySet()) {
                if (pos == 0) {
                    stringBuilder.append("?");
                }
                if (pos > 0) {
                    stringBuilder.append("&");
                }
                try {
                    stringBuilder.append(String.format("%s=%s", key, URLEncoder.encode(map.get(key), "utf-8")));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                pos++;
            }
            String requestUrl = url + stringBuilder.toString();
            //重点
            try {
                //新建一个url对象
                URL urls = new URL(requestUrl);
                //打开一个 HttpURLConnection 连接
                HttpURLConnection httpURLConnection = (HttpURLConnection) urls.openConnection();
                //设置连接主机超时时间
                httpURLConnection.setConnectTimeout(5 * 100);
                //设置从主机读取超时
                httpURLConnection.setReadTimeout(5 * 100);
                //设置是否使用缓存
                httpURLConnection.setUseCaches(true);
                //设置为 get 请求
                httpURLConnection.setRequestMethod("POST");  //get 和post有什么区别？
                //设置请求头信息
                httpURLConnection.setRequestProperty("Content-Type", "application/json");
                //设置客户端与服务连接类型
                httpURLConnection.addRequestProperty("Content-Type", "Keep-Alive");

                //开始连接
                httpURLConnection.connect();   // 这里如果不管的话，请求网络会报错
                //判断请求是否成功
                if (httpURLConnection.getResponseCode() == 200) {
                    //获取返回的json数据
                    result = streamToString(httpURLConnection.getInputStream());
                    //解析json数据
                    jsonObject = new JSONObject(result);
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return jsonObject;
    }

    public static String streamToString(InputStream in) throws IOException {
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = in.read(bytes)) != -1) {
            bs.write(bytes, 0, len);
        }
        in.close();
        bs.close();
        byte[] byteArray = bs.toByteArray();
        return new String(byteArray);
    }
}
